Skip to content

Live preview: frame drafts in the admin; frontend 0.5.0 - #7

Merged
blakebauman merged 9 commits into
mainfrom
feat/live-preview-on-own-names
Nov 10, 2026
Merged

blakebauman merged 9 commits into
mainfrom
feat/live-preview-on-own-names

Conversation

@blakebauman

Copy link
Copy Markdown
Contributor

What and why

A site on @contentworker/frontend can now be framed by the ContentWorker admin for live preview: the entry editor's Site view and the canvas. It follows the live preview channel spec, using the published @contentworker/[email protected] (connectPreview). Public pages are byte-identical to before: a golden test checks status, headers and body for six routes.

Preview handoff and cookie

  • /__preview?entry={id}#token={token}: a small no-store page reads the token from the fragment, strips it from history, and hands it over in a same-origin form POST. The token never reaches logs or the Referer. The ?token= form still works, for navigations only.
  • The grant cookie is HttpOnly; Secure; SameSite=None; Partitioned. Inside the admin's frame it stays in the admin's partition. An old unpartitioned cookie is cleared on grant and exit.
  • Framing: preview responses send frame-ancestors <admin origin>, which is CONTENTWORKER_ADMIN, or derived from the cdn./api. hosts. When no admin origin is known, or it equals the site's own origin, they send 'none'. They also send Referrer-Policy: no-referrer.
  • A safe /__preview/exit redirect.

Live preview

  • On preview pages, data-cw-ref paths mark blocks and their fields, through a new preview-only ctx.ref (sections[<key>], sections[<key>].heading), and data-cw-slot marks slots. Public renders carry none of this.
  • POST /__preview/render re-renders the changed blocks, or the whole <main> when that's safer, from the editor's unsaved fields. It goes through the same escaping renderers, needs the grant cookie, and is same-origin only.
  • scripts/live-preview.js connects through connectPreview. It reports the draft entry (capped at the SDK's 50), swaps blocks in place, renders Coworker's proposals as ghosts (data-cw-ghost, with a 381 B preview stylesheet), and drops out-of-order responses.
  • The SDK's live-preview build is vendored as static files: no bundler, its own 20 KB budget, 15,966 B now.
  • Links stay in preview: on /__preview pages, same-site page links stay under /__preview/ so browsing inside the frame stays in preview.
  • Token values checked everywhere: ctx.cssVars() is the one way to write CSS custom properties from content. Every value passes the SDK's isSafeTokenValue, on public and preview renders alike.

Versions: @contentworker/frontend 0.5.0. @contentworker/create-site 0.1.3 pins ^0.5.0.

Checked

  • npm run lint, npm run check-types: clean.
  • npm test: frontend 176/176, including the 6 golden byte-identity tests (regenerated against Give the frontend its own names; frontend 0.4.0 #4's output); create-site 7/7.
  • npm run budgets, all ok:
    • critical CSS 3018 B, critical JS 2886 B, deferred CSS 629 B;
    • preview JS 3426/4096 B, vendored SDK 15966/20480 B, preview CSS 382/1024 B;
    • idle JS 629 B.
  • npm run bundle: --dry-run: exiting now.
  • End to end in Chrome, against a real local ContentWorker admin, with the site on another site:
    • The Site view connects after the fragment handoff, and typed edits appear in the frame, escaped.
    • A click selects the block in the form.
    • The canvas draws seams from data-cw-slot, and inspector edits re-render the block.
    • The partitioned cookie works in the frame and isn't visible top-level.
    • Trusted Types blocks unapproved HTML.
  • Not run: Safari and Firefox.

Reviews:

  • Security review, two rounds: no critical or high findings. Fixed:
    • an open redirect on exit (/\host);
    • a planted grant through a subresource ?token=;
    • render amplification from repeated embedded links;
    • Trusted Types narrowed to live pages;
    • multi-policy CSP merging.
    • Accepted and documented: a preview link is a bearer link.
  • Code review: out-of-order renders, the page-head h1 on a first-block swap, the render locale check, legacy cookies, admin-origin normalization, CSS on whole-main swaps, duplicate keys, empty blocks, and link-index depth. All fixed.

Notes

  • The page reports only the draft entry, not its references, and field refs cover headings plus title and body. More marks can follow through ctx.ref.
  • The vendored SDK adds about 56 KB to the Worker bundle.

🤖 Generated with Claude Code

blakebauman and others added 9 commits November 7, 2026 16:12
- Fragment token handoff: /__preview?entry=<id>#token=<pw_…> answers a
  tiny no-store, noindex page whose (nonced) script drops the fragment
  from history and trades the token for the cookie with a same-origin
  POST /__preview (Origin checked, JSON only, 4 KB cap). ?token= still
  works; cw_session carries through to the draft URL.
- Preview cookie is SameSite=None; Secure; Partitioned (CHIPS), still
  HttpOnly and Path=/__preview, so it is sent inside the admin's frame
  and kept in the admin's partition.
- /__preview responses send frame-ancestors <admin origin> (derived from
  cdn./api.<domain>, or the new optional CONTENTWORKER_ADMIN; https only,
  never a wildcard; 'none' when unknown) and Referrer-Policy: no-referrer.
  withNonce now keeps a response's own directives. Public pages keep
  frame-ancestors 'self'.
- Preview-only markup: data-cw-slot on <main> for a blocks field,
  data-cw-block="<_key>" on block sections, data-cw-ref (the SDK's
  content-ref format, reimplemented in src/content-ref.ts) on the page's
  title and body. A test holds every public render free of them.
- POST /__preview/render re-renders blocks (or all of <main>) from
  unsaved draft fields with the page's own renderers, for the entry in
  the preview cookie only, token rechecked per call, same-origin JSON,
  2 MB cap, no-store, noindex.
- scripts/live-preview.js: a stub that will call startLivePreview from
  @contentworker/sdk/live-preview once it is published; loaded only
  under /__preview for the draft with cw_session. Budgeted at 4 KB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Security:
- /__preview/exit resolves `to` against the site and allows only a
  same-origin path (no /\host, tab-split or //host targets).
- A ?token= link sets the grant only for a navigation (Sec-Fetch-Dest
  document or iframe, or absent); subresource loads get a 403.
- A derived admin origin is logged once; an admin origin equal to the
  site's own frames nothing.
- The cw-preview Trusted Types policy is allowed only on live pages, and
  its createHTML passes only the markup a render response brought, once.
- nonceCsp handles a header joining several policies.

Review:
- Re-renders: a newer call aborts an older one, an older response is
  never drawn, and a superseded call settles only after the newest.
- The render endpoint answers all of <main> when a block swap could be
  wrong: the first section (it decides the h1), a missing key, or a key
  on two blocks; the client also refuses ambiguous keys. A block that
  renders to nothing is removed.
- A locale other than the site's is refused with 422.
- Grants clear the older unpartitioned SameSite=Lax cookie too; with
  several grants the matching one wins.
- A malformed CONTENTWORKER_ADMIN is normalised or logged and disables
  framing, instead of failing every render.
- Whole-<main> swaps keep stylesheets in <head>, once.
- The overlay's link index keeps the shallowest copy.
- Live pages drop the preview bar's exit link (public pages can't load
  in the admin's frame); link handling stays with the SDK's edit mode.
- A golden test holds public renders to origin/main's bytes and headers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On pages rendered for a live preview session (a valid cw_session and a
known admin), every link to one of the site's own pages becomes
/__preview/<path>?cw_session=<session>, so clicking around in the
admin's frame shows drafts where they exist and published content
elsewhere, instead of public pages that refuse to be framed. Only <a
href> to same-origin http(s) routes is rewritten; external, mailto:,
tel:, fragment-only and non-page links (files, Markdown twins) are left
alone. Done server-side on the runtime's own escaped markup, so no new
JS; re-rendered blocks get the same treatment when the live preview
script sends its session. A path with no draft keeps the session and
the preview bar (without the exit link) and loads no live script.
Public renders are unchanged (golden test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ContentWorker's docs/specs/live-preview-channel.md (and the SDK's
connectPreview) now govern the page side:

- No cw_session: the frontend mints its own channel. The handoff and the
  landing URL carry no session; the live preview script loads on every
  /__preview page showing the draft (with a known admin), and
  connectPreview stays a no-op unless framed.
- Links to the site's pages stay under /__preview/<path> on every
  preview page, with no session parameter. In a frame (Sec-Fetch-Dest:
  iframe) the preview bar drops its exit link.
- Marks follow the spec's content refs with field paths: data-cw-ref on
  each block (sections[<key>]) and on fields in it
  (sections[<key>].heading, through the new ctx.ref(field) that block
  renderers use), data-cw-slot holding the sections ref (the layout
  extension). data-cw-block is gone. src/content-ref.ts mirrors the SDK's
  formatFieldPath/parseFieldPath/blockKeyOf/topLevelField, escaping [, ]
  and % in keys, tested with the SDK's examples.
- POST /__preview/render takes one locale's values (onState's) and
  block refs, which must name this entry's sections[<key>] blocks in the
  site's space, environment and locale; it answers { ref, key, html }.
- The stub calls connectPreview({ adminOrigin, capabilities, onState })
  with select, patch.fields, patch.blocks, proposals, scroll and layout;
  onState renders view.withProposals, re-rendering only the blocks that
  changed, and marks view.ghosts with data-cw-ghost, styled by the new
  preview-only styles/preview.css (own 1 KB budget).
- frame-ancestors and the refusal of an admin origin equal to the site's
  stay as built. Public renders are unchanged (golden test).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Depend on @contentworker/sdk@^0.3.0. scripts/embed-assets.ts vendors
  its live-preview ESM build (the entry and the chunks it imports,
  unchanged, relative imports intact) into public/scripts/vendor/sdk/,
  gitignored and packed, with a .d.ts re-exporting the package's types
  for tsconfig.browser.json. Its own budget line (20 KB; 15,966 B today),
  recorded in docs/budget.md; check-budgets.ts learns directory groups.
- scripts/live-preview.js calls the real connectPreview with select,
  patch.fields, patch.blocks, proposals, scroll and layout; reports the
  draft first, at most PAGE_REPORT_LIMIT entries, on every connect; and
  on disconnect forgets what is on screen so the next session re-renders
  whole. A jsdom test runs the SDK from connect.offer through
  entry.state to applied.
- The Worker's content-ref helpers are now the SDK's own (tree-shaken:
  +18 B to the bundle).
- Token values checked everywhere: ctx.cssVars is the one way the
  runtime writes CSS custom properties from content, every value through
  the SDK's isSafeTokenValue on every render, unsafe values dropped
  whole. No runtime block writes one from content today.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The fragment handoff now submits the token in a same-origin form POST
  while the page is still parsing, answered with the grant cookie and a
  303 to the draft. The page is aborted before its load event, so a
  framing admin sees one page load: with the fetch-then-navigate version,
  the admin's Site pane took the handoff page's load for a navigation
  away from the entry ("The page moved away from this entry"). The
  handoff page's own Referrer-Policy is same-origin, so its POST carries
  Origin; POST /__preview takes only that form, from a navigation.
- npm run seed resolves a signed upload URL relative to the API (a local
  stack answers one); found seeding a local ContentWorker for the
  end-to-end check.
- frontend 0.4.0 (CHANGELOG out of Unreleased), create-site 0.1.2 uses
  it; READMEs cover live preview, the admin origin and ctx.cssVars.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Render amplification: each use of an embedded entry a link resolves to
  is charged its full size against the node budget, and a re-render over
  5 MB of HTML is refused, so a small body of repeated links can't make
  the Worker render one fragment tens of thousands of times.
- A www-twin redirect of a /__preview URL is no-store: its query can
  hold a legacy ?token=.
- A derived admin origin is logged at warn level (set
  CONTENTWORKER_ADMIN to name it).
- The vendoring step also refuses bare side-effect imports that aren't
  sibling files.
- Errors under /__preview keep the preview policy (frame-ancestors
  'none', no Referer, noindex).
- README: a preview link is a bearer link; prefer #token=.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings feat/live-preview (8eb69db..2a19702) onto refactor/own-names
(#4, frontend 0.4.0) and ports it to #4's names: the live preview
script uses enhance.js's enhanceSection(s); preview renders and tests
use data-section-state="pending", with-<block>, <block>-frame and
.prose; preview.css reads --color-link; budget groups and
docs/budget.md use critical/deferred/idle beside the preview groups.
The golden public renders are regenerated from #4's own code (b98dcf8,
rendered in a scratch worktree), so live preview is held to #4's bytes.
Depends on @contentworker/sdk ^0.3.0 (#4 had ^0.2.0).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
0.4.0 is #4's (the frontend's own names); live preview follows as
0.5.0, its CHANGELOG entry above #4's. create-site 0.1.3 pins ^0.5.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@blakebauman
blakebauman merged commit b741ad6 into main Nov 10, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant